<template>
  <!-- 项目编辑对话框 -->
  <el-dialog
    :title="
      editorReptileRow
        ? $t('reptileDialog.title.editor')
        : $t('reptileDialog.title.create')
    "
    :visible.sync="reptileCreatedDialogVisible"
    width="45%"
    @open="open()"
    :before-close="closeDialogCan"
  >
    <span class="main">
      <el-form
        ref="createdFormRef"
        :label-position="labelPosition"
        label-width="130px"
        :model="reptileCreatedForm"
        inline
        :rules="rules"
        ><el-form-item :label="$t('reptileDialog.form.en_name')" prop="en_name">
          <el-input
            v-model="reptileCreatedForm.en_name"
            :placeholder="placeholder"
            @change="changeEN"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('reptileDialog.form.project')"
          prop="project_id"
        >
          <el-select
            v-model="reptileCreatedForm.project_id"
            :placeholder="$t('reptileDialog.form.select')"
            style="width: 94%"
            @change="projectChange"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.ip
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('reptileDialog.form.cn_name')" prop="cn_name">
          <el-input v-model="reptileCreatedForm.cn_name"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('reptileDialog.form.category')"
          prop="site_category"
        >
          <!-- <el-input v-model="reptileCreatedForm.site_category"></el-input> -->
          <el-select
            multiple
            collapse-tags
            v-model="reptileCreatedForm.site_category"
            :placeholder="$t('reptileDialog.form.select')"
            style="width: 94%"
          >
            <el-option
              v-for="(item, index) in optionsClass"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="URL">
          <el-input v-model="reptileCreatedForm.target_url"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('reptileDialog.form.intro')"
          prop="website_introduction"
        >
          <el-input
            v-model="reptileCreatedForm.website_introduction"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('reptileDialog.form.webpage')"
          prop="sample_webpage"
        >
          <el-input v-model="reptileCreatedForm.sample_webpage"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('reptileDialog.form.descript')"
          prop="description"
        >
          <el-input v-model="reptileCreatedForm.description"></el-input>
        </el-form-item>
        <el-form-item :label="$t('reptileDialog.form.auth')" prop="auth">
          <el-input v-model="reptileCreatedForm.auth"></el-input>
        </el-form-item>
        <!-- <el-form-item label="依赖库" prop="dependent_file">
          <el-input v-model="reptileCreatedForm.dependent_file"></el-input>
        </el-form-item> -->
      </el-form>
      <!-- <input type="file" ref="file_input" /> -->
    </span>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialogCan">{{
        $t("reptileDialog.btn.cancel")
      }}</el-button>
      <el-button type="warning" plain @click="resetForm">{{
        $t("reptileDialog.btn.reset")
      }}</el-button>
      <el-button type="primary" @click="reptileCreated" style="width: 200px">{{
        editorReptileRow
          ? $t("reptileDialog.btn.save")
          : $t("reptileDialog.btn.create")
      }}</el-button>
      <!-- <el-button type="primary" @click="configContent">读取文件</el-button> -->
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: ["reptileCreatedDialogVisible", "editorReptileRow"],
  data() {
    var validateEn = (rule, value, callback) => {
      // console.log(this.reptileCreatedForm.project_id);
      // console.log(this.reptileList);
      // console.log(this.editorReptileRow);
      // console.log(value);
      // console.log(rule);
      // console.log(this.reptileCreatedForm.project_id);
      // 判断是编辑还是创建
      let validtType = 0;
      let reptileId = 0;
      if (this.editorReptileRow) {
        validtType = 1;
        reptileId = this.editorReptileRow.id;
      }
      if (this.reptileCreatedForm.project_id) {
        this.$http
          .get("/reptile/check_crawl_name", {
            params: {
              name: value,
              project_id: this.reptileCreatedForm.project_id,
              type: validtType,
              id: reptileId,
            },
          })
          .then((res) => {
            if (res.data.code != 0) {
              callback(new Error(this.$t("reptileDialog.message.have")));
            } else {
              callback();
            }
          });
      } else {
        callback();
      }
    };
    return {
      // 所有分类
      allCategory: [],
      // 当选择不同项目时的不同输入提示
      placeholder: "",
      optionsClass: [],
      options: [],
      labelPosition: "right",
      // 创建爬虫表单数据
      reptileCreatedForm: {},
      // 验证规则
      rules: {
        en_name: [
          {
            required: true,
            trigger: "blur",
            message: " ",
            // message: "爬虫名不能为空",
          },
          { validator: validateEn, trigger: "blur" },
        ],
        cn_name: [
          {
            required: true,
            trigger: "blur",
            message: " ",
            // message: "爬虫名不能为空",
          },
        ],
        target_url: [
          {
            required: true,
            trigger: "blur",
            message: " ",
            // message: "URL不能为空",
          },
        ],
        project_id: [
          {
            required: true,
            trigger: "blur",
            // message: "项目不能为空",
            message: "  ",
          },
        ],
      },
      // 主机列表
      // options: [],
      // 爬虫列表
      reptileList: [],
    };
  },
  methods: {
    async open() {
      // 获取所有分类
      this.getTags();
      // 获取所有项目列表
      const { data: res } = await this.$http.get("/task/list", {
        params: {
          page: 1,
          pagesize: 10,
          query_text: "",
          query_type: 1,
          task_type: 1,
        },
      });
      const { data: hostList } = await this.$http.get("/host");
      console.log(res.projects);
      console.log(hostList);
      res.projects.forEach((val) => {
        console.log(val.client_id);
        val.ip = hostList.find((vals) => {
          return vals.id == val.client_id;
        }).ip;
      });
      console.log(res.projects);

      this.options = res.projects;
      this.reptileList = res.reptiles;
      // console.log(this.editorReptileRow.site_category);
      // console.log(typeof this.editorReptileRow.site_category);
      if (this.editorReptileRow) {
        this.editorReptileRow.site_category =
          this.editorReptileRow.site_category.split("/");

        this.reptileCreatedForm = this.editorReptileRow;
        let selectProject = this.options.find((vals) => {
          return vals.id == this.editorReptileRow.project_id;
        });
        // this.optionsClass =
        //   selectProject.type == 1
        //     ? ["sns", "news", "think-tank", "audio", "video", "trajactory"]
        //     : ["audio", "ads", "ais", "other"];
        this.optionsClass = [];
        this.allCategory
          .filter((val) => {
            return val.type == selectProject.type;
          })
          .forEach((vals) => {
            this.optionsClass.push(vals.name);
          });
      } else {
        console.log(123456);
        this.reptileCreatedForm = {
          id: "",
          en_name: "",
          cn_name: "",
          site_category: [],
          target_url: "",
          website_introduction: "",
          sample_webpage: "",
          description: "",
          auth: "",
          dependent_file: "",
          project_id: "",
        };
      }
    },
    async getTags() {
      const { data: res } = await this.$http.get("/reptile/category_list");
      this.allCategory = res.data;
      console.log("---先看看全部爬虫分类---", res.data);
    },
    // 读取配置文件，获取爬虫类型(读取文件，获取文件内容)
    // configContent() {
    //   if (typeof FileReader == undefined)
    //     return this.$message.error(
    //       "此浏览器不支持文件读取，获取类别标签失败！"
    //     );
    //   // this.$refs.file_input.value = "..\\..\\爬虫类型配置文件.txt";
    //   // this.$message.success("浏览器支持文件读取！");
    //   console.log(this.$refs.file_input.files[0]);
    //   let file = this.$refs.file_input.files[0];
    //   let reader = new FileReader();
    //   reader.readAsText(file);
    //   // console.log(reader.readAsText(file));
    //   reader.onload = function (data) {
    //     // var tt = document.getElementById("tt");
    //     // tt.innerHTML = this.result;
    //     console.log(this.result);
    //   };
    // },
    // 验证爬虫名称不能重复
    // 当英文名称发生改变时
    changeEN(val) {
      console.log(val);
    },
    // 当项目发生改变时，
    projectChange(val) {
      this.reptileCreatedForm.site_category = [];
      console.log(val);
      let selectProject = this.options.find((vals) => {
        return vals.id == val;
      });
      // this.optionsClass =
      //   selectProject.type == 1
      //     ? ["sns", "news", "think-tank", "audio", "video", "trajactory"]
      //     : ["audio", "ads", "ais", "other"];
      this.optionsClass = [];
      this.allCategory
        .filter((val) => {
          return val.type == selectProject.type;
        })
        .forEach((vals) => {
          this.optionsClass.push(vals.name);
        });
      this.placeholder = selectProject.type == 2 ? "icaoName--radioName" : "";
    },
    // 创建爬虫
    reptileCreated() {
      this.$refs.createdFormRef.validate((valid) => {
        if (!valid) return;
        // console.log(this.reptileCreatedForm);
        this.reptileCreatedForm.site_category =
          this.reptileCreatedForm.site_category.join("/");
        console.log(this.reptileCreatedForm.site_category);
        this.$http
          .post("/reptile/created", this.reptileCreatedForm)
          .then((res) => {
            if (res.data.code == 0) {
              this.$refs.createdFormRef.resetFields();
              this.$message.success(
                this.editorReptileRow
                  ? this.$t("reptileDialog.message.editorSuccess")
                  : this.$t("reptileDialog.message.createSuccess")
              );
              this.closeDialog();
            } else {
              this.$message.error(
                this.editorReptileRow
                  ? this.$t("reptileDialog.message.editorError")
                  : this.$t("reptileDialog.message.createError")
              );
            }
          });
      });
    },
    resetForm() {
      this.$refs.createdFormRef.resetFields();
    },
    // 关闭弹出框
    closeDialog() {
      this.$emit("closeDialog");
    },
    closeDialogCan() {
      this.$emit("closeDialog", "1");
    },
  },
};
</script>

<style lang='less' scoped>
</style>